/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.app.balancer.handler;

import com.bugull.farm.core.balancer.Balancer;
import com.bugull.farm.core.balancer.LeastConnectionBalancer;
import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.frame.structure.Frame;
import com.bugull.farm.core.handler.Processor;
import com.bugull.farm.core.server.ZKClient;
import com.bugull.farm.core.utils.ByteUtil;
import io.netty.channel.ChannelHandlerContext;

/**
 * For command: CMD_APP_WORKER, get the worker server
 * 
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class AppWorkerProcessor implements Processor {

    @Override
    public void process(ChannelHandlerContext ctx, Frame frame) throws Exception {
        Balancer selector = new LeastConnectionBalancer(ZKClient.getInstance().getCurator());
        String ip = selector.select(PropertiesCache.getInstance().get("zk.app.workers"));
        if(ip == null){
            ctx.close();
            return;
        }
        String[] ipString = ip.split("\\.");
        byte[] ipBytes = new byte[4];
        for(int i=0; i<4; i++){
            ipBytes[i] = (byte)Integer.parseInt(ipString[i]);
        }
        byte[] portBytes = ByteUtil.fromShort((short)PropertiesCache.getInstance().getInt("app.server.port").intValue());
      //回复设备IP和端口信息
        frame.setBytes("ipaddress", ipBytes);
        frame.setBytes("port", portBytes);
        ctx.writeAndFlush(frame.getFastResponse());
    }

}
